<template>
  <div>
    <Modal
      :loading="modelOkLoad"
      :value="value"
      @on-cancel="handleCancelClick"
      @on-ok="handleOkClick"
      @on-visible-change="handleVisibleChange"
      title="修改密码"
    >
      <Form :label-width="90" :model="form" :rules="formRules" ref="form">
        <FormItem label="旧密码" prop="oldPassword">
          <Input
            @on-focus="handleResetModelLoading"
            placeholder="请输入旧密码"
            v-model="form.oldPassword"
          />
        </FormItem>
        <FormItem label="新密码" prop="newPassword">
          <Input
            @on-focus="handleResetModelLoading"
            placeholder="请输入新密码"
            type="password"
            v-model="form.newPassword"
          />
        </FormItem>
        <FormItem label="确认密码" prop="newPasswordRepeat">
          <Input
            @on-focus="handleResetModelLoading"
            placeholder="请输入确认密码"
            type="password"
            v-model="form.newPasswordRepeat"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import { changePassword } from '@/api/user.js';
import { mapMutations, mapActions } from 'vuex';

export default {
  model: {
    prop: 'value',
    event: 'on-visible-change'
  },
  props: {
    value: Boolean
  },
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        const reg = /^[a-z0-9]{6,18}$/i;
        if (!reg.test(value)) {
          callback(new Error('新密码规则：长度6-18位数字或字母'));
        } else {
          if (value == this.form.oldPassword) {
            callback(new Error('新密码与旧密码重复'));
          }
          if (this.form.newPasswordRepeat !== '') {
            // 对第二个密码框单独验证
            this.$refs.form.validateField('newPasswordRepeat');
          }
          callback();
        }
      }
    };
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      form: {
        oldPassword: '',
        newPassword: '',
        newPasswordRepeat: ''
      },
      formRules: {
        oldPassword: [{ required: true, message: '请输入旧密码' }],
        newPassword: [
          { required: true, message: '请输入新密码' },
          { validator: validatePass, trigger: 'blur' }
        ],
        newPasswordRepeat: [
          { required: true, message: '请再次输入密码' },
          { validator: validatePassCheck, trigger: 'blur' }
        ]
      },
      modelOkLoad: true
    };
  },
  methods: {
    ...mapActions(['handleLogOut']),

    // ...mapMutations({
    //   setToken: state => state.user.setToken,
    //   setAccess: state => state.user.setAccess
    // }),
    ...mapMutations(['setToken', 'setAccess']),
    handleVisibleChange (visible) {
      this.$emit('on-visible-change', visible);
    },
    handleOkClick () {
      this.modelOkLoad = false;
      this.$refs.form.validate(async valid => {
        try {
          if (valid) {
            this.modelOkLoad = true;
            const data = {
              oldPassword: this.form.oldPassword,
              newPassword: this.form.newPassword
            };
            const res = await changePassword(data);
            //  原密码不正确
            if (res.data.code == 201) {
              this.$Message.error(res.data.msg);
            } else {
            //  密码修改成功
              this.$Message.success('密码修改成功');
              this.$refs.form.resetFields();
              // this.setToken('');
              // this.setAccess([]);
              this.handleLogOut();
              this.$emit('on-visible-change', false);
            }
          }
        } catch (error) {
          console.error(error);
        }
      });
    },
    handleCancelClick () {
      this.$refs.form.resetFields();
    },
    handleResetModelLoading () {
      this.modelOkLoad = false;
      this.$nextTick(() => {
        this.modelOkLoad = true;
      });
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .ivu-modal-body {
  padding: 30px 90px 20px 30px;
}
.page-wrapper {
  .ivu-page {
    float: right;
    margin: 10px 0;
  }
}
</style>
